package com.service.purchase;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.excel.EasyExcel;
import com.common.DateUtils;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;
import com.dao.purchase.BillDao;
import com.dao.purchase.BillGoodDao;
import com.dao.purchase.BillGroupDao;
import com.dao.purchase.ReceiveGoodDao;
import com.dao.supply.InfoMapper;
import com.dao.supply.SupplyMapper;
import com.enums.WorkFlowIdModel;
import com.model.purchase.BillGoodModel;
import com.model.purchase.BillGroupModel;
import com.model.purchase.BillModel;
import com.model.purchase.BillVoModel;
import com.model.purchase.PurchaseSupplyDeal;
import com.model.purchase.ReceiveGoodModel;
import com.model.supply.SupplyInfoModel;
import com.model.supply.SupplyUserModel;
import com.model.sys.SysUser;
import com.service.external.oa.GetWFStatusService;
import com.service.external.sap.SapPurchaseService;

@Service
public class BillGroupService {
	static final Logger logger = LoggerFactory.getLogger(BillGroupService.class);

	@Autowired
	BillGroupDao billGroupDao;
	@Autowired
	CommonService commonService;
	@Autowired
	BillDao billDao;
	@Autowired
	BillGoodDao billGoodDao;
	@Autowired
	InfoMapper supplyMapper;
	@Autowired
	SapPurchaseService sapPurchaseService;
	@Autowired
	ReceiveGoodDao receiveGoodDao;

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<BillGroupModel> list = billGroupDao.selectList(queryMap);
		int count = billGroupDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	public HttpResult selectCheckList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("checkDeptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("checkUserId", sysUser.getUserid());
			}
		}
		List<BillGroupModel> list = billGroupDao.selectList(queryMap);
		int count = billGroupDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 详情
	 * 
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String groId) {
		HttpResult httpResult = new HttpResult();
		BillGroupModel billGroupModel = billGroupDao.load(groId);
		httpResult.setData(billGroupModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult save(BillVoModel billVoModel) {
		if (billVoModel == null) {
			return HttpResult.error("参数不能为空!");
		}
		if (billVoModel.getStatus().equals(Global.YES + "")) {
			if (billVoModel.getBillGoodModels() == null || billVoModel.getBillGoodModels().size() == 0) {
				return HttpResult.error("物资明细不能为空！");
			}
			if (billVoModel.getBillModels() == null || billVoModel.getBillModels().size() == 0) {
				return HttpResult.error("发票不能为空!");
			}
		}

		if (billVoModel.getStatus().equals(Global.YES + "")) {
			billVoModel.setCommitTime(DateUtils.getCurrentTime());
		}
		int result = 0;
		// 发票批次
		if (billVoModel.getBillGoodModels() != null && billVoModel.getBillGoodModels().size() > 0) {
			HashMap<String, Object> hashMap = new HashMap<String, Object>();
			hashMap.put("infCode", billVoModel.getBillGoodModels().get(0).getInfCode());
			List<SupplyInfoModel> infoModels = supplyMapper.selectList(hashMap);
			if (infoModels != null && infoModels.size() > 0) {
				billVoModel.setInfCode(infoModels.get(0).getInfId());
				billVoModel.setInfName(billVoModel.getBillGoodModels().get(0).getInfName());
			}
		}
		billVoModel.setSapStatus(Global.NO + "");
		if (!StringUtils.isNotNull(billVoModel.getGroId())) {
			billVoModel.setGroId(UUID.randomUUID().toString());
			billVoModel.setGroCode(commonService.createCode("purchase_bill_group", "gro_code"));
			result = billGroupDao.insert(billVoModel);
		} else {
			result = billGroupDao.update(billVoModel);
		}
		// 发票表
		if (billVoModel.getBillModels() != null) {
			billDao.deleteByGroId(billVoModel.getGroId());
			for (BillModel billModel : billVoModel.getBillModels()) {
				// 发票号是否已存在
				HashMap<String, Object> queryMap = new HashMap<String, Object>();
				queryMap.put("bilCode", billModel.getBilCode());
				int count = billDao.selectListCount(queryMap);
				if (count > 0) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return HttpResult.error(billModel.getBilCode() + ":发票号已存在");
				}
				// 保存
				billModel.setGroId(billVoModel.getGroId());
				billModel.setGroCode(billVoModel.getGroCode());
				billModel.setGroName(billVoModel.getGroName());
				billModel.setBilId(UUID.randomUUID().toString());
				billModel.setStatus(billVoModel.getStatus());
				billDao.insert(billModel);
			}
		}
		// 物资明细
		if (billVoModel.getBillGoodModels() != null) {
			billGoodDao.deleteByGroId(billVoModel.getGroId());
			for (BillGoodModel billGoodModel : billVoModel.getBillGoodModels()) {
				billGoodModel.setGroId(billVoModel.getGroId());
				billGoodModel.setGroCode(billVoModel.getGroCode());
				billGoodModel.setGroName(billVoModel.getGroName());
				billGoodModel.setStatus(billVoModel.getStatus());
				billGoodDao.insert(billGoodModel);
				if (billVoModel.getStatus().equals(Global.YES + "")) {
					// 交货单开票状态改为1
					ReceiveGoodModel receiveGoodModel = receiveGoodDao.load(billGoodModel.getGodId());
					receiveGoodModel.setStatus(Global.YES + "");
					receiveGoodDao.update(receiveGoodModel);
				}
			}
		}

		HttpResult httpResult = new HttpResult();
		if (result > 0) {
			httpResult.setMsg(billVoModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(billVoModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(billVoModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	@Transactional
	public HttpResult check(BillVoModel billVoModel) {
		if (billVoModel == null) {
			return HttpResult.error("参数不能为空!");
		}
		if (billVoModel.getSapStatus().equals(Global.YES + "")) {
			if (billVoModel.getBillGoodModels() == null || billVoModel.getBillGoodModels().size() == 0) {
				return HttpResult.error("物资明细不能为空！");
			}
			if (billVoModel.getBillModels() == null || billVoModel.getBillModels().size() == 0) {
				return HttpResult.error("发票不能为空!");
			}
		}
		SysUser sysUser = SpringMvcUtils.getSysUser();

		int result = 0;
		// 发票批次
		if (billVoModel.getBillGoodModels() != null && billVoModel.getBillGoodModels().size() > 0) {
			HashMap<String, Object> hashMap = new HashMap<String, Object>();
			hashMap.put("infCode", billVoModel.getBillGoodModels().get(0).getInfCode());
			List<SupplyInfoModel> infoModels = supplyMapper.selectList(hashMap);
			if (infoModels != null && infoModels.size() > 0) {
				billVoModel.setInfCode(infoModels.get(0).getInfId());
				billVoModel.setInfName(billVoModel.getBillGoodModels().get(0).getInfName());
			}
		}
		if (StringUtils.isNullOrEmpty(billVoModel.getCommitTime())) {
			billVoModel.setCommitTime(DateUtils.getCurrentTime());// 员工我的发票提交时
		}
		billVoModel.setCheckName(sysUser.getUsername());
		billVoModel.setCheckId(sysUser.getUserid());
		billVoModel.setCheckTime(DateUtils.getCurrentTime());
		billVoModel.setOaId(Global.NO + "");
		if (!StringUtils.isNotNull(billVoModel.getGroId())) {
			billVoModel.setGroId(UUID.randomUUID().toString());
			billVoModel.setGroCode(commonService.createCode("purchase_bill_group", "gro_code"));
			result = billGroupDao.insert(billVoModel);
		} else {
			result = billGroupDao.update(billVoModel);
		}
		// 发票表
		if (billVoModel.getBillModels() != null) {
			billDao.deleteByGroId(billVoModel.getGroId());
			for (BillModel billModel : billVoModel.getBillModels()) {
				if (StringUtils.isNullOrEmpty(billModel.getBilDate())) {
					return HttpResult.error("发票日期不能为空");
				}
				// 发票号是否已存在
				HashMap<String, Object> queryMap = new HashMap<String, Object>();
				queryMap.put("bilCode", billModel.getBilCode());
				int count = billDao.selectListCount(queryMap);
				if (count > 0) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return HttpResult.error(billModel.getBilCode() + ":发票号已存在");
				}
				// 保存
				billModel.setGroId(billVoModel.getGroId());
				billModel.setGroCode(billVoModel.getGroCode());
				billModel.setGroName(billVoModel.getGroName());
				billModel.setBilId(UUID.randomUUID().toString());
				billModel.setStatus(billVoModel.getStatus());
				billDao.insert(billModel);
			}
		}
		// 物资明细
		if (billVoModel.getBillGoodModels() != null) {
			billGoodDao.deleteByGroId(billVoModel.getGroId());
			for (BillGoodModel billGoodModel : billVoModel.getBillGoodModels()) {
				billGoodModel.setGroId(billVoModel.getGroId());
				billGoodModel.setGroCode(billVoModel.getGroCode());
				billGoodModel.setGroName(billVoModel.getGroName());
				billGoodModel.setStatus(billVoModel.getStatus());
				billGoodDao.insert(billGoodModel);
				if (billVoModel.getStatus().equals(Global.YES + "")) {
					// 交货单开票状态改为1
					ReceiveGoodModel receiveGoodModel = receiveGoodDao.load(billGoodModel.getGodId());
					receiveGoodModel.setStatus(Global.YES + "");
					receiveGoodDao.update(receiveGoodModel);
				}
			}
		}

		// 调用sap接口
		if (billVoModel.getSapStatus().equals(Global.YES + "")) {
			HttpResult sapHttpResult = sapPurchaseService.commitBill(billVoModel);
			if (sapHttpResult.getCode() == HttpStatus.SUCCESS_CODE) {
				if (StringUtils.isNullOrEmpty(null)) {
					billVoModel.setSapId(sapHttpResult.getData().toString());
				}
				billGroupDao.update(billVoModel);
			} else {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return HttpResult.error("sap返回：" + sapHttpResult.getMsg());
			}
		}

		HttpResult httpResult = new HttpResult();
		if (result > 0) {
			httpResult.setMsg(billVoModel.getSapStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(billVoModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(billVoModel.getSapStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult delete(String groId) {
		if (!StringUtils.isNotNull(groId)) {
			return HttpResult.error("参数不能为空");
		}
		BillGroupModel model = billGroupDao.load(groId);
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}

		HttpResult httpResult = new HttpResult();
		int result = billGroupDao.delete(groId);
		billDao.deleteByGroId(groId);
		billGoodDao.deleteByGroId(groId);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	@Autowired
	GetWFStatusService wfStatusService;

	@Transactional
	public HttpResult recall(String groId, String status) {
		if (!StringUtils.isNotNull(groId) || StringUtils.isNullOrEmpty(status)) {
			return HttpResult.error("参数不能为空");
		}

		SysUser sysUser = SpringMvcUtils.getSysUser();

		BillGroupModel billGroupModel = billGroupDao.load(groId);
		if (billGroupModel.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("当前状态未提交！");
		}
		if (StringUtils.isNotNull(billGroupModel.getOaId())) {
			// oa退回才可撤回
			HttpResult httpResultOa = wfStatusService.getToDoWorkflowRequestList(billGroupModel.getOaId(),
					sysUser.getWxid());
			if (httpResultOa.getCode() != HttpStatus.SUCCESS_CODE) {
				return httpResultOa;
			}
		}

		billGroupModel.setStatus(status);
		billGroupModel.setSapStatus(Global.NO + "");
		int result = billGroupDao.update(billGroupModel);

		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("groId", groId);
		List<BillModel> billModels = billDao.selectList(hashMap);
		for (BillModel billModel : billModels) {
			billModel.setStatus(Global.NO + "");
			result += billDao.update(billModel);
		}
		List<BillGoodModel> billGoodModels = billGoodDao.selectList(hashMap);
		for (BillGoodModel billGoodModel : billGoodModels) {
			billGoodModel.setStatus(Global.NO + "");
			result += billGoodDao.update(billGoodModel);
			// 交货单开票状态改为0
			ReceiveGoodModel receiveGoodModel = receiveGoodDao.load(billGoodModel.getGodId());
			receiveGoodModel.setStatus(Global.NO + "");
			receiveGoodDao.update(receiveGoodModel);
		}
		HttpResult httpResult = new HttpResult();

		if (result > 0) {
			httpResult.setMsg("回退成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	@Transactional
	public HttpResult recallAdmin(String groId, String status) {
		if (!StringUtils.isNotNull(groId) || StringUtils.isNullOrEmpty(status)) {
			return HttpResult.error("参数不能为空");
		}

		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			return HttpResult.error("无权限");
		}

		BillGroupModel billGroupModel = billGroupDao.load(groId);
		if (billGroupModel.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("当前状态未提交！");
		}
		if (StringUtils.isNotNull(billGroupModel.getOaId())) {
			// oa退回才可撤回
//			HttpResult httpResultOa = wfStatusService.getToDoWorkflowRequestList(billGroupModel.getOaId(),
//					sysUser.getWxid());
//			if (httpResultOa.getCode() != HttpStatus.SUCCESS_CODE) {
//				return httpResultOa;
//			}
		}

		billGroupModel.setStatus(status);
		billGroupModel.setSapStatus(Global.NO + "");
		int result = billGroupDao.update(billGroupModel);

		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("groId", groId);
		List<BillModel> billModels = billDao.selectList(hashMap);
		for (BillModel billModel : billModels) {
			billModel.setStatus(Global.NO + "");
			result += billDao.update(billModel);
		}
		List<BillGoodModel> billGoodModels = billGoodDao.selectList(hashMap);
		for (BillGoodModel billGoodModel : billGoodModels) {
			billGoodModel.setStatus(Global.NO + "");
			result += billGoodDao.update(billGoodModel);
			// 交货单开票状态改为0
			ReceiveGoodModel receiveGoodModel = receiveGoodDao.load(billGoodModel.getGodId());
			receiveGoodModel.setStatus(Global.NO + "");
			receiveGoodDao.update(receiveGoodModel);
		}
		HttpResult httpResult = new HttpResult();

		if (result > 0) {
			httpResult.setMsg("回退成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	@Transactional
	public HttpResult back(String groId) {
		HttpResult httpResult = new HttpResult();
		if (!StringUtils.isNotNull(groId)) {
			return HttpResult.error("参数不能为空");
		}

		BillGroupModel billGroupModel = billGroupDao.load(groId);
		billGroupModel.setStatus(Global.NO + "");
		int result = billGroupDao.update(billGroupModel);

		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("groId", groId);
		List<BillModel> billModels = billDao.selectList(hashMap);
		for (BillModel billModel : billModels) {
			billModel.setStatus(Global.NO + "");
			result += billDao.update(billModel);
		}
		List<BillGoodModel> billGoodModels = billGoodDao.selectList(hashMap);
		for (BillGoodModel billGoodModel : billGoodModels) {
			billGoodModel.setStatus(Global.NO + "");
			result += billGoodDao.update(billGoodModel);
			// 交货单开票状态改为0
			ReceiveGoodModel receiveGoodModel = receiveGoodDao.load(billGoodModel.getGodId());
			receiveGoodModel.setStatus(Global.NO + "");
			receiveGoodDao.update(receiveGoodModel);
		}

		if (result > 0) {
			httpResult.setMsg("回退成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<BillGroupModel> list = billGroupDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), BillGroupModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
